import React, { useRef, useState, useEffect } from 'react';
import { connect, history } from 'umi';
import TableDataBlock from '@/components/TableDataBlock';
import PopImgShow from '@/components/PopImgShow';
import { goodsType_status } from '@/common/contact'
import SetForm from './components/Form';
import moment from 'moment';
import Detail from './components/Details'
import DeleteModel from './components/DeleteModel'
import { onCommodity } from '@/common/historyLinkShop';
import ModalPrice from '@/components/ModalPrice';
import { Button } from 'antd'
import ShareApp from '@/components/ShareApp';
import './index.less'
const PlanList = (props) => {
  const { loading, dispatch, list } = props;
  const { location = {} } = history;
  const { query = {} } = location;
  const { id, type = 'list', accessId } = query;
  const childRef = useRef();
  const [categoryList, setCategoryList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false)
  const [priceVisible, setPriceVisible] = useState(false);
  const [deleteVisible, setDeleteVisible] = useState(false)
  const [shareVisible, setShareVisible] = useState(false);
  useEffect(() => {
    if (type === 'detail') {
      setDetailVisible({
        show: true,
        detail: {
          id,
        },
      });
    }
  }, []);
  const findParentIds = (data, childId, result = []) => {
    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      if (item.id === childId) {
        result.push(item.id);
        if (item.parentId) {
          findParentIds(data, item.parentId, result);
        }
        break;
      } else if (item.subGoodsCategoryList) {
        findParentIds(item.subGoodsCategoryList, childId, result);
        if (result.length > 0 && item.id) {
          result.push(item.id);
          break;
        }
      }
    }
    return result;
  };

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const rowSelection = {
    type: 'checkedBox',
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRows);
    },
    selectedRowKeys: selectedRowKeys.map((item) => {
      return item.id.toString();
    }),
    preserveSelectedRowKeys: true,
  };
  // 搜索参数
  useEffect(() => {
    fetchData();
  }, []);
  const fetchData = () => {
    dispatch({
      type: 'commodity/fetchListGoodsCategory',
      callback: (e) => {
        setCategoryList(e);
      },
    });
  };
  const searchItems = [
    {
      label: '商品名称',
      name: 'keyword',
    },
    {
      label: '上架状态',
      name: 'status',
      type: 'select',
      select: {
        0: '已下架',
        1: '已上架',
      },
    },
  ];

  // table 表头
  const getColumns = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '封面',
      dataIndex: 'cover',
      render: (val) => {
        return <PopImgShow url={val}></PopImgShow>
      }
    },
    {
      title: '浏览量/访客数/销量/退货数量',
      dataIndex: 'packageGoodsAmount',
      render: (e, record) => {
        const { viewAmount, viewUserAmount, saleAmount, returnAmount } = record
        return `${viewAmount}/${viewUserAmount}/${saleAmount}/${returnAmount}`
      }
    },
    {
      title: '售价',
      dataIndex: 'price',
      render: (e, record) => {
        return e ? (
          <Button
            type="link"
            onClick={() => {
              setPriceVisible({
                show: true,
                details: record,
              });
            }}
          >
            {e}
          </Button>
        ) : (
          '--'
        );
      },
    },
    {
      title: '库存',
      dataIndex: 'stock',
    },
    {
      title: '最高价格',
      dataIndex: 'skuHighPrice',
    },
    {
      title: '商品编码',
      dataIndex: 'goodsCode',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '包含商品数量',
      dataIndex: 'packageGoodsAmount',
    },

    {
      title: '状态',
      dataIndex: 'status',
      render: (e) => {
        return {
          0: '下架',
          1: '上架'
        }[e]
      }
    },
    {
      type: 'handle',
      width: 200,
      dataIndex: 'id',
      render: (val, record) => [
        {
          auth: true,
          title: '配置',
          click: () => {
            onCommodity({
              dispatch: dispatch,
              query: {
                id: val,
                type: 'detail',
              },
            });
          },
        },
        {
          auth: true,
          title: '分享',
          click: () => {
            setShareVisible({
              show: true,
              detail: record,
            });

          },
        },
        {
          auth: true,
          type: 'edit',
          click: () => {
            history.push({
              pathname: '/commodityModule/commodityEdit',
              query: {
                id: val,
                accessId
              }
            })
          },
        },
        {
          auth: true,
          title: record.status === '0' ? '上架' : '下架',
          click: () => {
            dispatch({
              type: record.status === '0' ? 'commodity/fakeUpOfflineGoods' : 'commodity/fakeDownOfflineGoods',
              payload: { goodsIdList: [val] },
              callback: () => {
                handleReload()
              }
            })
          },
        },
        {
          title: '删除',
          click: () => {
            setDeleteVisible({
              show: true,
              detail: record
            })
          },
        },
      ],
    },
  ];
  const handleCallback = () => {
    childRef.current.fetchGetData();
  };
  const handleReload = () => {
    childRef.current.reloadData();
  };
  const handleSaveRole = (detail = {}) => {
    setVisible(() => {
      return {
        show: true,
        detail,
      };
    });
  };
  const extraBtn = [
    {
      text: '批量上架',
      typeBtn: 'primary',
      onClick: () => {
        dispatch({
          type: 'commodity/fakeUpOfflineGoods',
          payload: {
            goodsIdList: selectedRowKeys.map((item) => {
              return item.id.toString();
            }),
          },
          callback: () => {
            setSelectedRowKeys([])
            handleReload()
          }
        })
      },
    },
    {
      text: '批量下架',
      typeBtn: 'default',
      onClick: () => {
        dispatch({
          type: 'commodity/fakeDownOfflineGoods',
          payload: {
            goodsIdList: selectedRowKeys.map((item) => {
              return item.id.toString();
            }),
          },
          callback: () => {
            setSelectedRowKeys([])
            handleReload()
          }
        })
      },
    },
    {
      text: '新增',
      onClick: () => {
        history.push({
          pathname: '/commodityModule/commodityEdit',
          query: {

            accessId
          }
        })
      },
    },
  ]
  if (!detailVisible) {
    return (
      <>
        <TableDataBlock
          rowSelection={rowSelection}
          cardProps={{ title: '实物商品' }}
          btnExtra={extraBtn}
          cRef={childRef}
          loading={loading}
          searchItems={searchItems}
          columns={getColumns}
          rowKey={(record) => `${record.id}`}
          dispatchType="commodity/fetchListOfflineGoods"
          {...list}
        ></TableDataBlock>
        <SetForm
          childRef={childRef}
          visible={visible}
          onClose={() => setVisible(false)}
          handleCallback={handleCallback}
        ></SetForm>
        <ShareApp visible={shareVisible} onClose={() => setShareVisible(false)}></ShareApp>
        <ModalPrice
          handleReload={handleReload}
          visible={priceVisible}
          onClose={() => setPriceVisible(false)}
        ></ModalPrice>
        <DeleteModel handleCallback={handleCallback} onClose={() => setDeleteVisible(false)} visible={deleteVisible}></DeleteModel>
      </>
    );
  }
  else {
    return <Detail
      setEditVisible={(e) => {
        setDetailVisible(() => {
          const {
            goodsPropertyList = [],
            goodsSkuList = []
          } = e
          const { upDelayTime, upType, categoryId } = e
          setVisible({
            show: true,
            detail: {
              ...e,
              goodsPropertyList: goodsPropertyList.map(item => {
                const {
                  propertyCover,
                  propertyName,
                  propertyValue = ''
                } = item
                return {
                  showImage: propertyCover ? ['add'] : '',
                  image: propertyCover,
                  name: propertyName,
                  valueList: propertyValue.split(',').map(val => {
                    return {
                      value: val
                    }
                  })
                }
              }),
              goodsSkuList: goodsSkuList.map(item => {
                const { propertyDesc = '' } = item
                return {
                  ...item,
                  properties: propertyDesc.split(',').map(val => {
                    let property = val.split(':')
                    return {
                      name: property[0],
                      value: property[1]
                    }
                  })
                }
              }),
              categoryId: findParentIds(categoryList, Number(categoryId)).reverse(),
              upDelayTime: upType === 'delay' ? moment(upDelayTime) : ''
            }
          })
          return false
        })
      }}
      visible={detailVisible}
      onClose={() => setDetailVisible(false)}
      handleCallback={handleCallback}
      dispatch={dispatch}
    ></Detail>
  }

};

export default connect(({ commodity, loading }) => ({
  list: commodity.offlineGoodsList,
  loading: loading.effects['commodity/fetchListOfflineGoods'],
}))(PlanList);
